<template>
	<view class="container">
		<image class="bg" src="/static/login/top-bg.png" mode="aspectFill"></image>

		<view class="app-welcome-title">
			<view class="top-back-btn" @click="toBack">
				<image class="top-back" src="/static/login/close.png" mode="aspectFill"></image>
			</view>
			<view class="">{{wayIndex == 3 ?  "注册" : "登录账号"}}</view>
		</view>

		<view class="login-form-wrap">
			<!-- 验证码登录 -->
			<view v-if="wayIndex === 1" class="way-content">
				<view class="input-row-item">
					<view class="input-item-title">邮箱</view>
					<view class="input-wrap">
						<image src="@/static/login/user.png" mode="aspectFill"></image>
						<view class="input-box">
							<input type="text" placeholder="请输入您的邮箱" :maxlength="emailMaxlength"
								v-model="submitData.login" placeholder-class="placeholderClass" />
						</view>
						<view class="select-account"
							:style="{transform: showAccountPicker ? 'rotate(180deg)' : 'rotate(0deg)'}"
							@click="handleItemEvent({action:'accountPicker'})">
							<u-icon name="arrow-down" color="#b5b5b5" size="18"></u-icon>
						</view>
					</view>
				</view>
				<view class="input-row-item">
					<view class="input-item-title">验证码</view>
					<view class="input-wrap">
						<image src="@/static/login/yzm.png" mode="aspectFill"></image>
						<view class="input-box">
							<input type="number" placeholder="请输入验证码" :maxlength="yzmMaxlength"
								v-model="submitData.code" placeholder-class="placeholderClass" />
						</view>
						<view class="yzm-btn" :class="loginCoding ? 'coding-bg' : ''"
							@click="handleItemEvent({action:'code'})">
							<!-- {{loginCodeTips}}
							<u-code uniqueKey="login-code" :seconds="loginSeconds" changeText="X秒"
								@start="loginCodeStart" @end="loginCodeEnd" ref="loginUCode"
								@change="loginCodeChange"></u-code> -->
							<smsCode ref="loginUCode" />
						</view>
					</view>
				</view>
			</view>

			<!-- 密码登录 -->
			<view v-if="wayIndex === 2" class="way-content">
				<view class="input-row-item">
					<view class="input-item-title">邮箱</view>
					<view class="input-wrap">
						<image src="@/static/login/user.png" mode="aspectFill"></image>
						<view class="input-box">
							<input type="text" placeholder="请输入您的邮箱" :maxlength="emailMaxlength"
								v-model="submitData.login" placeholder-class="placeholderClass" />
						</view>
						<view class="select-account"
							:style="{transform: showAccountPicker ? 'rotate(180deg)' : 'rotate(0deg)'}"
							@click="handleItemEvent({action:'accountPicker'})">
							<u-icon name="arrow-down" color="#b5b5b5" size="18"></u-icon>
						</view>
					</view>
				</view>
				<view class="input-row-item">
					<view class="input-item-title">密码</view>
					<view class="input-wrap">
						<image src="@/static/login/suo.png" mode="aspectFill"></image>
						<view class="input-box">
							<input type="password" placeholder="请输入密码" :maxlength="pswMaxlength"
								v-model="submitData.password" placeholder-class="placeholderClass" />
						</view>
					</view>
				</view>
			</view>

			<!-- 注册 -->
			<view v-if="wayIndex === 3" class="way-content register-content">
				<view class="input-row-item">
					<view class="input-item-title">邮箱（必填）</view>
					<view class="input-wrap">
						<image src="@/static/login/email.png" mode="aspectFill"></image>
						<view class="input-box">
							<input type="text" placeholder="请输入您的邮箱" :maxlength="emailMaxlength"
								v-model="submitData.email" placeholder-class="placeholderClass" />
						</view>
					</view>
				</view>
				<view class="input-row-item">
					<view class="input-item-title">验证码</view>
					<view class="input-wrap">
						<image src="@/static/login/yzm.png" mode="aspectFill"></image>
						<view class="input-box">
							<input type="number" placeholder="请输入验证码" :maxlength="yzmMaxlength"
								v-model="submitData.emailCode" placeholder-class="placeholderClass" />
						</view>
						<view class="yzm-btn" :class="emailCoding ? 'coding-bg' : ''"
							@click="handleItemEvent({action:'code'})">
							<!-- {{emailCodeTips}}
							<u-code uniqueKey="register-code" :seconds="emailSeconds" changeText="X秒"
								@start="emailCodeStart" @end="emailCodeEnd" ref="emailUCode"
								@change="emailCodeChange"></u-code> -->
							<smsCodeSuper ref="emailUCode" />
						</view>
					</view>
				</view>
				<view class="input-row-item">
					<view class="input-item-title">密码({{passwordGuide}})</view>
					<view class="input-wrap">
						<image src="@/static/login/suo.png" mode="aspectFill"></image>
						<view class="input-box">
							<input type="password" :placeholder="passwordTip" :maxlength="pswMaxlength"
								v-model="submitData.password" placeholder-class="placeholderClass" />
						</view>
						<!-- <view style="font-size: 26rpx;color:#969696;position: absolute;right: 0;bottom: -40rpx;">
							{{passwordGuide}}
						</view> -->
					</view>
				</view>
				<view class="input-row-item">
					<view class="input-item-title">确认密码</view>
					<view class="input-wrap">
						<image src="@/static/login/suo.png" mode="aspectFill"></image>
						<view class="input-box">
							<input type="password" placeholder="请再次输入上面密码" :maxlength="pswMaxlength"
								v-model="submitData.password_confirm" placeholder-class="placeholderClass" />
						</view>
					</view>
				</view>
				<view class="input-row-item">
					<view class="input-item-title">邀请码（必填）</view>
					<view class="input-wrap">
						<image src="@/static/login/yqm.png" mode="aspectFill"></image>
						<view class="input-box">
							<input type="text" placeholder="请输入邀请码（必填）" :maxlength="yzmMaxlength"
								v-model="submitData.inviteCode" placeholder-class="placeholderClass" />
						</view>
					</view>
				</view>
			</view>

			<view class="bottom-content">
				<view class="agreement-row" @click.stop="handleSelectAgree">
					<view class="gou-icon-box">
						<image v-if="isAgree" src="/static/login/gou1.png" mode="aspectFill"></image>
						<image v-else src="/static/login/gou0.png" mode="aspectFill"></image>
					</view>
					我已阅读并同意 <view class="web-url" @click.stop="handleItemEvent({action:'userAgreement'})">《服务协议》
					</view> 和
					<view class="web-url" @click.stop="handleItemEvent({action:'privacyAgreement'})">《隐私政策》</view>
				</view>
			</view>
			<view v-if="wayIndex == 3" class="login-btn register-btn" @click="handleItemEvent({action:'register'})">
				注册
			</view>
			<view v-else class="login-btn" @click="handleItemEvent({action:'login'})">
				登录
			</view>

			<!-- 登录过的账号选择 -->
			<u-picker :closeOnClickOverlay="true" :defaultIndex="defaultIndex" :show="showAccountPicker"
				:columns="accountsList" confirmColor="#FFE269" @cancel="showAccountPicker = false"
				@confirm="handlePickerConfirm"></u-picker>
		</view>

		<view v-if="wayIndex === 3" class="lr-tip-row">
			已有一个账号？
			<view class="now-register" @click="handleItemEvent({action:'switchLogin'})">
				去登录
				<image src="/static/login/right-arrow.png" mode="aspectFill"></image>
			</view>
		</view>
		<view v-else class="lr-tip-row">
			还没有账号？
			<view class="now-register" @click="handleItemEvent({action:'switchRegister'})">
				注册一个
				<image src="/static/login/right-arrow.png" mode="aspectFill"></image>
			</view>
		</view>

		<view v-if="wayIndex != 3" class="login-way-change">
			<view class="way-desc">
				<text>或者</text>
			</view>
			<view v-if="wayIndex == 1" class="login-btn way-btn" @click="handleItemEvent({action:'pswlogin'})">
				密码登录
			</view>
			<view v-if="wayIndex == 2" class="login-btn way-btn" @click="handleItemEvent({action:'smslogin'})">
				验证码登录
			</view>
		</view>

		<view v-if="wayIndex === 3" style="height: 200rpx;"></view>

		<loginNoitce ref="refLoginNoitce" @noticeAgree="handleNoticeAgree" />
	</view>
</template>

<script>
	import loginNoitce from "@/components/loginNoitce/loginNoitce.vue"
	import smsCode from "@/components/smsCode/smsCode.vue"
	import smsCodeSuper from "@/components/smsCodeSuper/smsCodeSuper.vue"
	import {
		sms,
		authRegister,
		loginBySmsAndPsw,
		userProfile
	} from "@/api/user.js"
	import {
		validateEmail,
		validatePassword
	} from "@/util/helper.js"

	const defaultLoginWay = 2;
	const inviteCode = "543126";
	const defaultForm = {
		login: "",
		emailCode: '',
		email: "",
		code: "",
		password: '',
		password_confirm: '',
		inviteCode
	}

	export default {
		components: {
			loginNoitce,
			smsCode,
			smsCodeSuper
		},
		data() {
			return {
				wayIndex: defaultLoginWay, // 1-验证码登录；2-密码登录；3-注册
				emailMaxlength: 30,
				pswMaxlength: 20,
				yzmMaxlength: 6,
				submitData: {
					login: "",
					emailCode: '',
					email: "",
					code: "",
					password: '',
					password_confirm: '',
					inviteCode
				},
				isAgree: false,

				loginCodeTips: "",
				loginSeconds: 60,
				loginCoding: false,

				emailCodeTips: "获取验证码",
				emailSeconds: 60,
				emailCoding: false,

				redirect: '',
				passwordTip: getApp().globalData.passwordTip,
				passwordGuide: getApp().globalData.passwordGuide,

				accountsList: [
					[]
				],
				defaultIndex: [
					[0]
				],
				showAccountPicker: false
			};
		},
		onLoad(o) {
			this.redirect = o.redirect ? decodeURIComponent(o.redirect) : ''
			// 安卓用框架自带的隐私弹框（解决上架问题：uniapp框架底层用户未同意隐私政策前获取OAID等信息），ios是自定义的
			if (!getApp().globalData.isAndroid) {
				setTimeout(() => {
					this.$refs.refLoginNoitce && this.$refs.refLoginNoitce.show()
				}, 600)
			}
		},
		onShow() {
			// 取出本地登录过的账号，供选择
			const _localAccountList = uni.getStorageSync("localAccountList");
			const accountOption = []
			if (!this.isEmpty(_localAccountList)) {
				for (let key in _localAccountList) {
					accountOption.push(_localAccountList[key].email)
				}
			}
			this.accountsList = [accountOption]
		},
		methods: {

			// 注册
			async handleRegister() {
				if (this.isEmpty(this.submitData.email)) {
					uni.showToast({
						title: "请输入邮箱",
						icon: "none"
					})
					return
				}
				if (!validateEmail(this.submitData.email)) {
					uni.showToast({
						title: "输入邮箱有误",
						icon: "none"
					})
					return
				}
				if (this.isEmpty(this.submitData.emailCode)) {
					uni.showToast({
						title: "请输入验证码",
						icon: "none"
					})
					return
				}
				if (this.isEmpty(this.submitData.password)) {
					uni.showToast({
						title: "请输入密码",
						icon: "none"
					})
					return
				}
				if (this.submitData.password.length < 6) {
					uni.showToast({
						title: this.passwordTip,
						icon: "none"
					})
					return
				}

				if (!validatePassword(this.submitData.password)) {
					uni.showToast({
						title: getApp().globalData.passwordGuide,
						icon: "none",
						duration: 4000
					})
					return
				}

				if (this.isEmpty(this.submitData.password_confirm)) {
					uni.showToast({
						title: "请输入确认密码",
						icon: "none"
					})
					return
				}
				if (this.submitData.password_confirm.length < 6) {
					uni.showToast({
						title: this.passwordTip,
						icon: "none"
					})
					return
				}

				if (!validatePassword(this.submitData.password_confirm)) {
					uni.showToast({
						title: getApp().globalData.passwordGuide,
						icon: "none",
						duration: 4000
					})
					return
				}

				if (this.submitData.password !== this.submitData.password_confirm) {
					uni.showToast({
						title: "两次密码输入不一致",
						icon: "none"
					})
					return
				}
				if (this.isEmpty(this.submitData.inviteCode)) {
					uni.showToast({
						title: "请输入邀请码",
						icon: "none"
					})
					return
				}

				if (!this.checkIsAgree()) return
				uni.showLoading({
					title: "注册中...",
					mask: true
				})
				await authRegister({
					email: this.submitData.email,
					emailCode: this.submitData.emailCode,
					password: this.submitData.password,
					inviteCode: this.submitData.inviteCode
				})

				this.submitData = defaultForm;
				uni.hideLoading();
				uni.showToast({
					title: "注册成功",
					icon: "success",
					mask: true,
					duration: 2000
				})

				this.verifyUserInfo();
			},

			// 处理登录
			async handleLogin() {
				if (this.isEmpty(this.submitData.login)) {
					uni.showToast({
						title: "请输入邮箱",
						icon: "none"
					})
					return
				}
				if (!validateEmail(this.submitData.login)) {
					uni.showToast({
						title: "输入邮箱有误",
						icon: "none"
					})
					return
				}
				if (this.wayIndex === 1) {
					if (this.isEmpty(this.submitData.code)) {
						uni.showToast({
							title: "请输入验证码",
							icon: "none"
						})
						return
					}
				} else {
					// 密码登录
					if (this.isEmpty(this.submitData.password)) {
						uni.showToast({
							title: "请输入密码",
							icon: "none"
						})
						return
					}
				}

				if (!this.checkIsAgree()) return

				uni.showLoading({
					title: "登录中...",
					mask: true
				})
				const params = {
					login: this.submitData.login,
				}
				if (this.wayIndex == 1) {
					params["code"] = this.submitData.code;
				} else {
					params["password"] = this.submitData.password;
				}

				let results = await loginBySmsAndPsw(params);

				uni.showToast({
					title: "登录成功",
					icon: "success",
					mask: true
				})
				uni.setStorageSync("userInfo", results.data);
				getApp().globalData.userInfo = results.data;
				uni.setStorageSync('subAccountChange', true)
				this.verifyUserInfo();
			},

			async getCode() {
				if (this.wayIndex == 1) {
					if (this.isEmpty(this.submitData.login)) {
						uni.showToast({
							title: "请输入邮箱",
							icon: "none"
						})
						return
					}
					if (!validateEmail(this.submitData.login)) {
						uni.showToast({
							title: "输入邮箱有误",
							icon: "none"
						})
						return
					}

					if (this.$refs.loginUCode.canGetCode) {
						uni.showLoading({
							title: '正在发送验证码'
						})
						await sms({
							email: this.submitData.login
						});

						uni.showToast({
							title: "验证码已发您邮箱",
							icon: "none",
							duration: 3000
						})

						// 通知验证码组件内部开始倒计时
						this.$refs.loginUCode.start();
					}

					return
				}

				// 注册
				if (this.isEmpty(this.submitData.email)) {
					uni.showToast({
						title: "请输入邮箱",
						icon: "none"
					})
					return
				}
				if (!validateEmail(this.submitData.email)) {
					uni.showToast({
						title: "输入邮箱有误",
						icon: "none"
					})
					return
				}
				if (this.$refs.emailUCode.canGetCode) {
					uni.showLoading({
						title: '正在发送验证码'
					})
					await sms({
						email: this.submitData.email
					});

					uni.showToast({
						title: "验证码已发您邮箱",
						icon: "none",
						duration: 3000
					})

					// 通知验证码组件内部开始倒计时
					this.$refs.emailUCode.start();
				}
			},

			handleItemEvent(val) {
				const {
					action
				} = val
				switch (action) {
					case 'switchLogin': //登录
					case 'smslogin': // 验证码登录
						this.wayIndex = 1
						break;
					case 'switchRegister': // 注册
						this.wayIndex = 3
						break;
					case 'pswlogin': // 密码登录
						this.wayIndex = 2
						break;
					case 'userAgreement': // 服务协议
						this.toPages("/pages/common/webView?src=" + getApp().globalData.staticConfig.register_agreement)
						break;
					case 'privacyAgreement': // 隐私协议
						this.toPages("/pages/common/webView?src=" + getApp().globalData.staticConfig.privacy_agreement)
						break;
					case 'code': // 获取验证码
						this.getCode()
						break;
					case 'login': // 登录
						this.handleLogin()
						break;
					case 'register': // 注册
						this.handleRegister()
						break;

					case "accountPicker": //选择登录过的账号
						if (JSON.stringify(this.accountsList) == "[[]]") {
							uni.showToast({
								title: "本地未登录过账号，无可选账号",
								icon: "none",
								duration: 3000
							})
							return
						}
						this.showAccountPicker = true;
						break;
				}
			},

			handlePickerConfirm(vals) {
				this.submitData.login = vals.value[0];
				this.showAccountPicker = false;
			},

			checkIsAgree() {
				if (this.isAgree) return true
				uni.showToast({
					title: '请阅读并勾选《服务协议》和《隐私协议》',
					icon: "none"
				})
				return false
			},

			async verifyUserInfo() {
				// 注册成功，切换到登录状态
				if (this.wayIndex == 3) {
					this.wayIndex = defaultLoginWay;

					setTimeout(() => {
						uni.showToast({
							title: "请用刚注册的账号登录",
							icon: "none",
							duration: 3000
						})
					}, 2000)
					return
				}

				// 验证码登录|密码登录成功
				const _userInfo = uni.getStorageSync('userInfo');
				if (this.isEmpty(_userInfo)) {
					uni.showModal({
						title: "",
						content: "客户端本地未查询到用户信息，请重新登录",
						showCancel: false,
						success: () => {
							this.wayIndex = defaultLoginWay;
						}
					})
					return
				}

				uni.showLoading({
					title: "加载中...",
					mask: true
				})

				const result = await userProfile();

				const updateUserInfo = {
					...getApp().globalData.userInfo,
					...result.data
				}

				// 本地登录过的账号列表
				const _localAccountList = uni.getStorageSync("localAccountList") || {};
				_localAccountList[`${updateUserInfo.email}`] = updateUserInfo;
				uni.setStorageSync("localAccountList", _localAccountList);

				uni.setStorageSync("userInfo", updateUserInfo);
				getApp().globalData.userInfo = updateUserInfo;

				// 重置
				this.submitData = defaultForm;

				if (this.redirect) {
					uni.redirectTo({
						url: this.redirect
					})
					return
				}
				uni.switchTab({
					url: "/pages/tabbar/home/home",
					success: () => {
						uni.hideLoading();
					}
				})
			},

			handleSelectAgree() {
				this.isAgree = !this.isAgree;
			},

			loginCodeChange(text) {
				this.loginCodeTips = text;
			},
			loginCodeStart() {
				this.loginCoding = true;
			},
			loginCodeEnd() {
				this.loginCoding = false
			},

			emailCodeChange(text) {
				this.emailCodeTips = text;
			},
			emailCodeStart() {
				this.emailCoding = true;
			},
			emailCodeEnd() {
				this.emailCoding = false
			},

			handleNoticeAgree() {
				// this.handleAgree()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		padding: 0 40rpx;

		.bg {
			position: fixed;
			top: 0;
			left: 0;
			bottom: 0;
			right: 0;
			width: 100vw;
			height: 310rpx;
			z-index: -1;
		}

		.login-btn {
			width: 670rpx;
			height: 92rpx;
			line-height: 92rpx;
			border-radius: 12rpx;
			background: #FFE269;
			display: block;
			text-align: center;
			font-size: 32rpx;
			font-weight: 600;
			color: #26282B;
			margin: 0 auto;
		}

		.app-welcome-title {
			width: 100%;
			font-size: 48rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: #26282B;
			text-align: left;
			margin: 116rpx auto 20rpx 0;

			.top-back-btn {
				width: 60rpx;
				height: 60rpx;
				margin: 0 0 48rpx auto;
				display: flex;
				align-items: center;
				justify-content: center;

				.top-back {
					width: 44rpx;
					height: 44rpx;
				}
			}
		}

		.login-form-wrap {
			margin: 0 0 0 0;

			.way-content {
				.input-row-item {
					.input-item-title {
						font-size: 26rpx;
						color: #7B828A;
						margin: 32rpx 0 12rpx 0;
					}

					.input-wrap {
						height: 96rpx;
						border: 1px solid #DBE0E6;
						border-radius: 12rpx;
						display: flex;
						align-items: center;
						position: relative;

						image {
							width: 40rpx;
							height: 40rpx;
							margin: 0 28rpx;
						}

						.input-box {
							height: 100%;
							flex: 1;
							padding-right: 28rpx;

							input {
								border: 0;
								width: 100%;
								height: 100%;
								font-size: 28rpx;
							}
						}

						.yzm-btn {
							width: 196rpx;
							height: 76rpx;
							line-height: 76rpx;
							font-size: 26rpx;
							font-family: PingFang SC-Medium, PingFang SC;
							font-weight: 500;
							color: #26282B;
							text-align: center;
							background-color: #FFE269;
							border-radius: 12rpx;
							margin-right: 10rpx;
							overflow: hidden;
						}

						.coding-bg {
							background-color: #D2D9E1;
						}

						.placeholderClass {
							color: #969696;
							font-size: 28rpx;
						}

						.select-account {
							width: 80rpx;
							height: 100%;
							display: flex;
							align-items: center;
							justify-content: center;
							transform: rotate(-90deg);
							transition: 0.3s ease;
						}
					}
				}
			}

			.register-content {}

			.oper-login {
				width: 580rpx;
				height: 70rpx;
				line-height: 70rpx;
				text-align: center;
				font-size: 28rpx;
				color: #ffffff;
				border-radius: 35rpx;
				margin: 0rpx auto 40rpx auto;
				background: #3479f5;
			}
		}

		.lr-tip-row {
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			font-family: PingFang SC-Regular, PingFang SC;
			font-weight: 400;
			color: #A6ACB4;
			line-height: 33rpx;
			margin-top: 32rpx;

			.now-register {
				color: #D6A909;
				display: flex;
				align-items: center;

				image {
					width: 28rpx;
					height: 28rpx;
				}
			}
		}

		.bottom-content {
			flex: 1;
			display: flex;
			margin: 32rpx 0 60rpx 0;

			.agreement-row {
				height: 34rpx;
				line-height: 34rpx;
				font-size: 24rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #A6ACB4;
				display: flex;

				.gou-icon-box {
					width: 32rpx;
					height: 32rpx;
					margin-right: 20rpx;
				}

				image {
					width: 100%;
					height: 100%;
				}

				.web-url {
					color: #005AEC;
				}
			}

		}

		.login-way-change {
			flex: 1;
			display: flex;
			align-content: flex-end;
			flex-direction: column;
			justify-content: flex-end;
			padding-bottom: 60rpx;

			.way-desc {
				width: 670rpx;
				height: 1px;
				background-color: #DBE0E6;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0 auto;

				text {
					padding: 10rpx 30rpx;
					background-color: #ffffff;
					font-size: 26rpx;
					color: #7B828A;
				}
			}

			.way-btn {
				background-color: #EEF1F6;
				margin-top: 52rpx;
			}
		}
	}
</style>